<?php

class ArticleController extends Controller
{
  /**
   * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
   * using two-column layout. See 'protected/views/layouts/column2.php'.
   */
  public $layout = '//layouts/column2';
  
  /**
   * @return array action filters
   */
  public function filters()
  {
    return array(
      'accessControl' // perform access control for CRUD operations
      //'postOnly + delete', // we only allow deletion via POST request
    );
  }
  
  /**
   * Specifies the access control rules.
   * This method is used by the 'accessControl' filter.
   * @return array access control rules
   */
  public function accessRules()
  {
    return array(
      array(
        'allow', // allow authenticated user to perform 'create' and 'update' actions
        'actions' => array(
          'index',
          'view',
          'create',
          'update',
          'sort',
          'delete'
        ),
        'users' => array(
          '@'
        )
      ),
      array(
        'deny', // deny all users
        'users' => array(
          '*'
        )
      )
    );
  }
  
  /**
   * Displays a particular model.
   * @param integer $id the ID of the model to be displayed
   */
  public function actionView($id)
  {
    $model      = $this->loadModel($id);
    $model_lang = $this->loadModelLang($id, Yii::app()->session['language']);
    $this->render('view', array(
      'model' => $model,
      'model_lang' => $model_lang
    ));
  }
  
  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate()
  {
    $model          = new Article;
    $model->enabled = 1;
    
    if (isset($_POST['Article'])) {
      $model->attributes  = $_POST['Article'];
      $model->description = $_POST['Article']['description'];
      $model->detail      = $_POST['Article']['detail'];
      
      $transaction = Yii::app()->db->beginTransaction();
      
      try {
        if ($model->validate()) {
          $model->title2       = ($_POST['Article']['title2'] != '') ? $_POST['Article']['title2'] : '{translate}';
          $model->description2 = ($_POST['Article']['description2'] != '') ? $_POST['Article']['description2'] : '{translate}';
          $model->detail2      = ($_POST['Article']['detail2'] != '') ? $_POST['Article']['detail2'] : '{translate}';
          //Insert image
          if (CUploadedFile::getInstanceByName('Article[image]')) {
            $file            = new File();
            $photo           = CUploadedFile::getInstanceByName('Article[image]');
            $file->filename  = $photo->getName();
            $file->filesaved = encodeFilename(time() . '_' . $photo->getName());
            $file->filetype  = 'image';
            $file->folder    = 'article/post-images';
            $photo->saveAs('upload/article/post-images/' . $file->filesaved);
            $file->save();
            $model->image = $file->id;
            //thumbnail 
            $thumb        = Yii::app()->image->load(Yii::getPathOfAlias("webroot") . "/upload/article/post-images/" . $file->filesaved);
            $thumbnails   = Article::model()->thumbnails;
            foreach ($thumbnails as $thumbnail) {
              $thumb->resize($thumbnail[0], $thumbnail[1]);
              $thumb->save(Yii::getPathOfAlias("webroot") . "/upload/article/thumbs_$thumbnail[0]x$thumbnail[1]/" . $file->filesaved); //save vao thumb
            }
          }
          
          $model->save();
          foreach (array(
            'vi',
            'en'
          ) as $item) {
            $lang              = new ArticleLang();
            $lang->articleID   = $model->id;
            $lang->title       = ($item == 'vi') ? $model->title : $model->title2;
            $lang->description = ($item == 'vi') ? $model->description : $model->description2;
            $lang->detail      = ($item == 'vi') ? $model->detail : $model->detail2;
            $lang->languageID  = $item;
            $lang->save();
          }
          $transaction->commit();
          $this->redirect(array(
            'view',
            'id' => $model->id
          ));
        }
      }
      catch (Exception $e) {
        $transaction->rollBack();
      }
    }
    $this->render('create', array(
      'model' => $model
    ));
  }
  
  /**
   * Updates a particular model.
   * If update is successful, the browser will be redirected to the 'view' page.
   * @param integer $id the ID of the model to be updated
   */
  public function actionUpdate($id)
  {
    $model               = $this->loadModel($id);
    $vn                  = $this->loadModelLang($id, 'vi');
    $en                  = $this->loadModelLang($id, 'en');
    $model->title        = $vn->title;
    $model->title2       = $en->title;
    $model->description  = $vn->description;
    $model->description2 = $en->description;
    $model->detail       = $vn->detail;
    $model->detail2      = $en->detail;
    
    //Image
    $image = File::model()->getFile($model->image);
    
    if (isset($_POST['Article'])) {
      $model->attributes = $_POST['Article'];
      $model->description = $_POST['Article']['description'];
      $model->detail      = $_POST['Article']['detail'];
      
      $transaction = Yii::app()->db->beginTransaction();
      
      try {
        if ($model->validate()) {
          $model->title2       = ($_POST['Article']['title2'] != '') ? $_POST['Article']['title2'] : $model->title2;
          $model->description2 = ($_POST['Article']['description2'] != '') ? $_POST['Article']['description2'] : $model->description2;
          $model->detail2      = ($_POST['Article']['detail2'] != '') ? $_POST['Article']['detail2'] : '{translate}';
          //Insert image
          if (CUploadedFile::getInstanceByName('Article[image]')) {
            //Delete old image
            if (!empty($image) && file_exists(Yii::app()->basePath . "/../upload/article/post-images/" . $image['save'])) {
              @unlink(Yii::getPathOfAlias("webroot") . "/upload/article/post-images/" . $image['save']);
              $thumbnails = Article::model()->thumbnails;
              foreach ($thumbnails as $thumbnail) {
                if (file_exists(Yii::app()->basePath . "/../upload/article/thumbs_$thumbnail[0]x$thumbnail[1]/" . $image['save'])) {
                  @unlink(Yii::getPathOfAlias("webroot") . "/upload/article/thumbs_$thumbnail[0]x$thumbnail[1]/" . $image['save']);
                }
              }
              $file = File::model()->findByPk($model->image);
              if (!empty($file)) {
                $file->delete();
              }
            }
            //Insert new image
            $file            = new File();
            $photo           = CUploadedFile::getInstanceByName('Article[image]');
            $file->filename  = $photo->getName();
            $file->filesaved = encodeFilename(time() . '_' . $photo->getName());
            $file->filetype  = 'image';
            $file->folder    = 'article/post-images';
            $photo->saveAs('upload/article/post-images/' . $file->filesaved);
            $file->save();
            $model->image = $file->id;
            //thumbnail 
            $thumb        = Yii::app()->image->load(Yii::getPathOfAlias("webroot") . "/upload/article/post-images/" . $file->filesaved);
            $thumbnails   = Article::model()->thumbnails;
            foreach ($thumbnails as $thumbnail) {
              $thumb->resize($thumbnail[0], $thumbnail[1]);
              $thumb->save(Yii::getPathOfAlias("webroot") . "/upload/article/thumbs_$thumbnail[0]x$thumbnail[1]/" . $file->filesaved); //save vao thumb
            }
          }
          
          $model->save();
          $vn->title       = $model->title;
          $vn->description = $model->description;
          $vn->detail      = $model->detail;
          $vn->update();
          $en->title       = $model->title2;
          $en->description = $model->description2;
          $en->detail      = $model->detail2;
          $en->update();
          $transaction->commit();
          $this->redirect(array(
            'view',
            'id' => $model->id
          ));
        }
      }
      catch (Exception $e) {
        $transaction->rollBack();
      }
    }
    
    $this->render('update', array(
      'model' => $model,
      'image' => $image
    ));
  }
  
  /**
   * Deletes a particular model.
   * If deletion is successful, the browser will be redirected to the 'admin' page.
   * @param integer $id the ID of the model to be deleted
   */
  public function actionDelete($id)
  {
    $model   = $this->loadModel($id);
    
    $image = File::model()->getFile($model->image);
    //Delete old image
    if (!empty($image) && file_exists(Yii::app()->basePath . "/../upload/article/post-images/" . $image['save'])) {
      @unlink(Yii::getPathOfAlias("webroot") . "/upload/article/post-images/" . $image['save']);
      $thumbnails = Article::model()->thumbnails;
      foreach ($thumbnails as $thumbnail) {
        if (file_exists(Yii::app()->basePath . "/../upload/article/thumbs_$thumbnail[0]x$thumbnail[1]/" . $image['save'])) {
          @unlink(Yii::getPathOfAlias("webroot") . "/upload/article/thumbs_$thumbnail[0]x$thumbnail[1]/" . $image['save']);
        }
      }
      $image->delete();
    }
    $articleLangs = $model->articleLangs;
    if (!empty($articleLangs)) {
      foreach ($articleLangs as $articleLang) {
        $articleLang->delete();
      }
    }
    $model->delete();
    
    // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
    if (!isset($_GET['ajax']))
      $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array(
        'index'
      ));
  }
  
  
  /**
   * Manages all models.
   */
  public function actionIndex()
  {
    $model = new Article('search');
    $model->unsetAttributes(); // clear any default values
    if (isset($_GET['Article']))
      $model->attributes = $_GET['Article'];
    
    if (isset($_GET['pageSize'])) {
      Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']);
      unset($_GET['pageSize']); // would interfere with pager and repetitive page size change
    }
    
    $articles = Article::model()->findAll($model->search()->criteria);
    
    $this->render('index', array(
      'model' => $model,
      'articles' => $articles
    ));
  }
  
  public function actionSort()
  {
    if (Yii::app()->request->isAjaxRequest) {
      if (isset($_POST['items']) && is_array($_POST['items'])) {
        $i = 0;
        foreach ($_POST['items'] as $item) {
          $article       = Article::model()->findByPk($item);
          $article->sort = $i;
          $article->update();
          $i++;
        }
      }
    }
  }
  
  /**
   * Returns the data model based on the primary key given in the GET variable.
   * If the data model is not found, an HTTP exception will be raised.
   * @param integer $id the ID of the model to be loaded
   * @return Article the loaded model
   * @throws CHttpException
   */
  public function loadModel($id)
  {
    $model = Article::model()->findByAttributes(array(
      'id' => $id,
    ));
    if ($model === null)
      throw new CHttpException(404, 'The requested page does not exist.');
    return $model;
  }
  
  public function loadModelLang($id, $lang)
  {
    $model = ArticleLang::model()->findByAttributes(array(
      'articleID' => $id,
      'languageID' => $lang
    ));
    if ($model === null)
      $model = new ArticleLang();
    return $model;
  }
  /**
   * Performs the AJAX validation.
   * @param Article $model the model to be validated
   */
  protected function performAjaxValidation($model)
  {
    if (isset($_POST['ajax']) && $_POST['ajax'] === 'article-form') {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }
  }
}